<template>
    <div class="container">
        <h1>评论管理-vuex版</h1>
        <hr>
        <!-- 发布评论 -->
        <cmt-post @addComment="addHandler"></cmt-post>
        <hr>
        <!-- <h5>评论条数({{this.$store.getters.commentsCount}})</h5> -->
        <h5><b>评论条数({{commentsCount}})</b></h5>
        <div class="list-group">
            <!-- 评论单项 -->
            <cmt-item
                v-for="(item) in comments"
                :key="item.id"
                :item="item"
                @delComment="delHandler"
            ></cmt-item>
        </div>
    </div>
</template>
<script>
// 导入vuex相关方法:mapState(映射属性),mapMutations(映射方法)
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
import CmtPost from "./CmtPost";
import CmtItem from "./CmtItem";
export default {
    components: {
        CmtPost,
        CmtItem
    },
    data() {
        return {};
    },
    // 调用mapState将vuex中的state映射成组件的计算属性
    computed: {
        // ...mapState({
        //     comments: state => state.comments.comments
        // }),
        // 将this.comments映射为this.$store.state.comments.comments
        ...mapState('comments',['comments']),
        // 将commentsCount映射为this.$store.getters.commentsCount
        ...mapGetters("comments",['commentsCount'])
    },
    created() {
        this.getInitComments();
    },
    methods: {
        // 将 `this.addComment()` 映射为 `this.$store.commit('comments/addComment',comment)`
        // 将 `this.delComment()` 映射为 `this.$store.commit('comments/delComment',id)`
        ...mapMutations('comments',['delComment','addComment']),
        // 将 `this.getInitComments()` 映射为 `this.$store.dispatch('comments/getInitComments')`
        ...mapActions('comments',['getInitComments']),
        // 删除评论(自定义事件处理函数)
        delHandler(id) {
            // this.comments=this.comments.filter(item=>id!=item.id);
            // 调用store对象的删除方法
            // this.$store.commit('comments/delComment',id)
            this.delComment(id);
        },
        // 发布评论(自定义事件处理函数)
        addHandler(comment) {
            // this.comments.unshift(comment)
            // 调用vuex提供的添加方法
            // this.$store.commit('addComment',comment)
            this.addComment(comment);
        }
    }
};
</script>
<style scoped lang="css">
</style>